package algorithm.weightgraph;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class DenseWeightGraph<Weight extends Number&Comparable> extends AbstractGraph<Weight> {

    private Edge<Weight>[][] edges;


    public DenseWeightGraph(int pointNums, boolean directed){
        this.pointNums = pointNums;
        this.directed = directed;
        this.edges = new Edge[pointNums][pointNums];
    }


    @Override
    public void addEdge(int s, int e, Weight weight) {
        //如果存在，则覆盖掉之前的
        if (hasEdge(s,e)){
            edges[s][e] = null;
            if (!directed){
                edges[e][s]=null;
            }
            edgeNums--;
        }

        edges[s][e] = new Edge<>(s,e,weight);
        if (!directed){
            edges[e][s] = new Edge<>(e,s,weight);
        }
        edgeNums++;
    }


    @Override
    public boolean hasEdge(int s, int e) {
        return edges[s][e]==null;
    }

    @Override
    public Iterator<Edge<Weight>> getIterator(int s) {
        List<Edge<Weight>> list = new LinkedList<>();
        for (Edge<Weight> edge : edges[s]) {
            if (edge!=null){
                list.add(edge);
            }
        }
        return list.iterator();
    }

    @Override
    public void show() {
        for (Edge<Weight>[] edgeArr : edges) {
            for (Edge<Weight> edge : edgeArr) {
                String msg = (edge == null ? "0.00" : edge.getWeight()+"");
                if (msg.length()<4){
                    for (int i = 0; i < 4-msg.length(); i++) {
                        msg+="0";
                    }
                }
                System.out.print(msg+"\t");
            }
            System.out.println();
        }
    }
}
